#add image with alpha channel
import Image
import os
def conver_alpha_png(fname,maskcolor):
	img = Image.open(fname)
	newname = fname.split('.')[0] + ".png"
	if img.mode == "P":
		img = img.transpose(Image.FLIP_TOP_BOTTOM)
	if img.mode != "RGBA":  
		img = img.convert("RGBA")
	pix = img.load()
	(width,height) = img.size
	for i in range(width):
		for j in range(height):
			if pix[i,j] == maskcolor:
				pix[i,j] = (255,255,255,0)
	print "convert %s to %s"%(fname,newname)
	img.save(newname)
	
def conver_alpha_png_by_max_color(fname):
	img = Image.open(fname)
	if img.mode != "RGBA":  
		img = img.convert("RGBA")
	colors = img.getcolors()
	colors.sort()
	print colors
	conver_alpha_png(fname,colors[-1][-1])
	
def conver_alpha_png_by_max_color_path(fname):
	for p,_,files in os.walk(fname):
		for fname in files:
			if fname.split('.')[-1] == "png":
				continue
			fullpath = os.path.join(p,fname)
			conver_alpha_png_by_max_color(fullpath)
			
def conver_alpha_png_by_color_path(fname,maskcolor):
	for p,_,files in os.walk(fname):
		for fname in files:
			if fname.split('.')[-1] == "png":
				continue
			fullpath = os.path.join(p,fname)
			conver_alpha_png(fullpath,maskcolor)
	
conver_alpha_png_by_color_path(r"img",(0,255,0,255))